package system

import org.apache.commons.lang.builder.HashCodeBuilder

class StaffMemberRole implements Serializable {

    StaffMember staffMember
    Role role

    @Override
    boolean equals(other) {
        if (!(other instanceof StaffMemberRole)) {
            return false
        }

        other.staffMember?.id == staffMember?.id &&
                other.role?.id == role?.id
    }

    @Override
    int hashCode() {
        def builder = new HashCodeBuilder()
        if (staffMember) builder.append(staffMember.id)
        if (role) builder.append(role.id)
        builder.toHashCode()
    }

    static StaffMemberRole get(String userId, String roleId) {
        find ('from StaffMemberRole where staffMember.id=:userId and role.id=:roleId',
                [userId: userId, roleId: roleId])
    }

    static StaffMemberRole create(StaffMember staffMember, Role role, boolean flush = false) {
        if (!StaffMemberRole.findByStaffMemberAndRole(staffMember, role))
            new StaffMemberRole(staffMember: staffMember, role: role).save(flush: flush, insert: true)
        else
            null
    }
    //2012-2-15 fang add        为用户批量添加权限
    static createManyRoles(StaffMember staffMember, Set<Role> roles, boolean flush = false) {
        roles.each {
            // new system.StaffMemberRole(staffMember: staffMember, role: it).save(flush: flush, insert: true)
            StaffMemberRole.create(staffMember as StaffMember, it as Role, flush)
        }

    }

    static boolean remove(StaffMember staffMember, Role role, boolean flush = false) {
        StaffMemberRole instance = StaffMemberRole.findByStaffMemberAndRole(staffMember, role)
        if (!instance) {
            return false
        }
        instance.delete(flush: flush)
        println("用户" + staffMember + "移除权限 " + role + " 成功")
        true
    }

//    static void removeAll(StaffMember staffMember,int flag=0) {      //0全部 1,只删除可展示的,2,只删除不可展示的
//        if(flag==1){
//            def list=Role.findAllByShowToJm(true)
//            executeUpdate 'DELETE FROM system.StaffMemberRole WHERE role in (:list) and staffMember.id=:staffMember', [list:list,staffMember: staffMember.id]
//        }
//        else if(flag==2){
//            def list=Role.findAllByShowToJm(false)
//            executeUpdate 'DELETE FROM system.StaffMemberRole WHERE role in (:list) and staffMember.id=:staffMember', [list:list,staffMember: staffMember.id]
//        }
//        else
//            executeUpdate 'DELETE FROM system.StaffMemberRole WHERE staffMember.id=:staffMember', [staffMember: staffMember.id]
//    }

    static void removeAll(Role role) {
        executeUpdate 'DELETE FROM StaffMemberRole WHERE role=:role', [role: role]
    }

    static mapping = {
        id composite: ['role', 'staffMember']
        version false
    }
}
